import numpy as np
import cv2

import sys
import os
from datetime import datetime
import random
# print(os.path.join(os.path.dirname(__file__), '..'))
# sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'face_recog', 'deploy'))

from model.RetinaDetectFaceModel import RetinaDetectFaceModel
from utils import log_util

class FaceRetinaModel():

    def __init__(self, dictProperties):
        self.retina_model = RetinaDetectFaceModel(dictProperties)


    def detect_face(self, frame):
        log_util.logger.debug('人脸特征提取-retina截取人脸开始')
        error, faces = self.retina_model.detect_faces(frame)
        if error is not None:
            return error, None, None, None, None
        if faces is None or len(faces) == 0:
            return ('400', '检测不到人脸'), None, None, None, None

        face_imgs = []
        bboxs = []
        is_masks = []
        face_angles = []
        for face in faces:
            bbox = face['box']
            w, h = bbox[2], bbox[3]
            box = np.array([bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3]])
            # ali_img = frame[int(box[1]):int(box[3]), int(box[0]):int(box[2])]
            ali_img = face['nimg']
            # dir = './imgs'  # + '/' + userCode
            # if not os.path.exists(dir):
            #     os.makedirs(dir)
            # num = 'catch' + datetime.now().strftime("%m-%d-%Y-%H-%M-%S") + '-' + str(random.randint(1, 10))
            # # 写原图
            # cv2.imwrite(dir + '/' + num + ".jpg", ali_img)

            img = cv2.cvtColor(ali_img, cv2.COLOR_BGR2RGB)
            img = cv2.resize(img, (112, 112))

            face_imgs.append(img)
            bboxs.append(bbox)
            is_masks.append(face['is_mask'])
            face_angles.append(face['face_angle'])
        log_util.logger.debug('人脸特征提取-retina截取人脸结束')
        return None, face_imgs, bboxs, is_masks, face_angles